package com.jason.ordermd.service;

import com.jason.common.dubboapi.IAccountServiceApi;
import com.jason.common.dubboapi.IProductServiceApi;
import com.jason.ordermd.domain.OrderDomain;
import com.jason.ordermd.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Random;

@Service
public class OrderService {
    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IAccountServiceApi iAccountServiceApi;
    @Autowired
    private IProductServiceApi iProductServiceApi;

    public OrderService() {
    }

    @GlobalTransactional(rollbackFor = RuntimeException.class)
    //@ShardingTransactionType(TransactionType.BASE)
    public void payOrder(){
        logger.info("pay begin");
        int random = new Random().nextInt(3);
        Long accountId = 10000000001L+random;
        Long productId = 10000L;
        BigDecimal am = new BigDecimal("1");

        OrderDomain orderDomain = new OrderDomain();
        orderDomain.setAccountId(accountId);
        orderDomain.setOrderStatus(1);
        orderDomain.setProductId(productId);
        orderMapper.insertOrder(orderDomain);
        try {
            iAccountServiceApi.addAmount(null, accountId, am);
            iProductServiceApi.reduceStore(null,productId);
        }catch (Exception e) {
            logger.error(e.getMessage(),e);
            throw  e;
        }
        logger.info("测试完成");
        //throw new RuntimeException("测试回滚");
    }

    @GlobalTransactional(rollbackFor = RuntimeException.class)
    //@ShardingTransactionType(TransactionType.BASE)
    public void payOrderRollBack(){
        logger.info("payOrderRollBack begin");
        Long accountId = 10000000001L;
        Long productId = 10000L;
        BigDecimal am = new BigDecimal("100");

        OrderDomain orderDomain = new OrderDomain();
        orderDomain.setAccountId(accountId);
        orderDomain.setOrderStatus(1);
        orderDomain.setProductId(productId);
       // orderMapper.insertOrder(orderDomain);

        iAccountServiceApi.addAmount(null,accountId,am);
        iProductServiceApi.reduceStore(null,productId);
        logger.info("测试回滚，准备抛出");
        throw new RuntimeException("测试回滚");
    }

    public void testThrowException(){
        logger.info("testThrowException begin");
        iProductServiceApi.testThrowException();
        logger.info("testThrowException，end");
    }
}
